let spuId;
let goodsBox
let sortWeightIdInfo = "sort-weight";
let frmSortWeightIdInfo = "frm-lose-weight";
let sortWeightId = sortWeightIdInfo;
//type:0:称重；1:报损
let sortTyp = 0;

$(document).ready(function () {

    initSortTable(null, null);
    packList();
    Cookies.remove('boxCode');
    Cookies.remove('checkWeight');
    $('[data-toggle="tooltip"]').tooltip();

    $("#select-id").selectpicker("refresh");
    //render方法强制重新渲染引导程序 - 选择ui,如果当您编程时更改任何相关值而影响元素布局，这将非常有用。
    $('#select-id').selectpicker('render');
    $(".selectpicker").on("changed.bs.select", function (e) {
        spuId = $(this).val();
    });

    //称重按钮
    $('#check-weight').on("click", function (e) {
        const input = $(this).val();
        checkWeight(input);
    });

    $("#sort-change-shifts").on("click", function (e) {
        sortChangeShifts();
    });

    //报损显示弹窗
    $('#frm-lose-model').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        console.log(">>>>>>>>>>" + JSON.stringify(button));
        var recipient = button.data('whatever'); // 解析出data-whatever内容
        $('#frm-loss-button').removeAttr("disabled");
        if (recipient) {
            var modal = $(this);
            modal.find('.modal-title').text('Message To ' + recipient);
            modal.find('.modal-body input').val(recipient);
        }
    });

    //报损隐藏弹窗
    $('#frm-lose-model').on('hide.bs.modal', function (event) {
        console.log("隐藏》》》》》》》");
        $('#goods-detail-id').val("");
        $('#frm-lose-weight').val("");
        $('#frm-loss-button').removeAttr("disabled");
        $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);

        clearInterval(sortSetInterval);
        sortWeightId = sortWeightIdInfo;
        sortTyp = 0;
        sortWeightInfo('sort-table', sortWeightId, sortTyp, 0, null, 1);
        const std = $('#sort-table').bootstrapTable('getData');
        if (Array.isArray(std) && std.length > 0) {
            const objBox = std[0];
            $("#sort-weight").val(objBox.weight);
        }
    });

    //报损下拉
    // $('#frm-lose-select').selectpicker('render');
    $("#frm-lose-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-detail-id').val(temp);
    });

    //降级原料下拉
    // $('#frm-spu-select').selectpicker('render');
    $("#frm-spu-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });

    //降级等级下拉
    // $('#frm-spu-grade-select').selectpicker('render');
    $("#frm-spu-grade-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });

    //降级标准下拉
    /*$('#demotion-standard-select').selectpicker('render');
    $("#demotion-standard-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
    });*/

    //降级显示弹窗
    $('#frm-demotion-model').on('show.bs.modal', function (event) {
    });

    //降级隐藏弹窗
    $('#frm-demotion-model').on('hide.bs.modal', function (event) {
        $('#demotion-goods-detail-box-code').val("");
        $('#demotion-goods-detail-id').val("");
        $('#frm-spu-select').selectpicker('val', ['noneSelectedText']);
        $('#frm-spu-grade-select').selectpicker('val', ['noneSelectedText']);
        $('#demotion-standard-select').selectpicker('val', ['noneSelectedText']);
    });

    $('#sort-table').on('check.bs.table', function (e, row, $element) {
        console.log("选中的行：" + JSON.stringify(row));
        $('#spu-img').attr('src', row.imgUrl);
        $('#sort-weight').val(row.weight);
    });

    sortWeightInfo('sort-table', sortWeightId, sortTyp, 0, null, 1);

});


let packs;

/**
 * 获取包装袋列表
 */
function packList() {
    const opt = {};
    $.ajax({
        type: "POST",
        url: "/system/pack/sort/list",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.length > 0) {
                        packs = data.data;
                    } else {
                    }
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

/**
 * 包装袋select下拉列表
 */
function packsToSelect(value, row, index) {
    let selectHtml = '';
    if (packs && packs.length > 0) {
        let selectOptions = '';
        selectOptions += '<option>请选择</option>';
        for (let i = 0; i < packs.length; i++) {
            const pack = packs[i];
            console.log("packsToSelect:" + value + ";" + pack.id);
            if (value && value == pack.id) {
                selectOptions += '<option value="' + pack.id + '" selected>' + pack.name + '</option>';
            } else {
                selectOptions += '<option value="' + pack.id + '">' + pack.name + '</option>';
            }

        }
        selectHtml = '<select class="pack-select" onchange="changeClick(this,' + row.id + ',' + index + ')">' + selectOptions + '</select>';
    }
    return selectHtml;
}

function changeClick(obj, rowId, index) {
    $('#pack-select option').each(function () {
        //取消掉正在选中的
        $(this).attr("selected", false);
    });
    console.log("选择的包装袋：" + JSON.stringify(obj.value));
    $('#sort-table').bootstrapTable('updateCell', {
        index: index,
        field: 'packId',
        value: obj.value
    });
    $('#pack-select').find("option[value='" + obj.value + "']").prop("selected", true);
}

//净重响应
function weighRespCallBack(obj, cancel, opt) {
    if (!obj) {
        return;
    }
    console.log("称重响应：" + JSON.stringify(obj));
    $('#check-weight').show();
    if (!cancel) {
        const data = obj.data;
        delResponseFromWcs(obj, opt);
        if (data.code == 0) {

        } else {
            BootstrapDialog.alert(data.msg);
        }
    }
}

//分拣称重
function sortWeightCallBack(obj, cancel, opt) {
    if (!obj) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(obj));
    if (!cancel) {
        delResponseFromWcs(obj, opt);
        const data = obj.data;
        if (data.code == 0) {
        } else {
        }
    }
}

function storageDoneCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (!cancel) {
        const obj = data.data;
        if (obj.code == 0) {
        } else {
        }
    }
}

//货箱离开缓存位
function leaveBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {

        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

//到达缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        console.log("无缓存数据");
        return;
    }
    console.log("到达缓存位：" + JSON.stringify(data));
    if (!cancel) {
        const obj = data.data;
        if (obj.code == 1) {

        } else {
        }
    }
}

//分拣称重socketIo响应
function electronicWeightCallBack(data) {
    console.log("称重数据返回：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.weight) {
            sortWeightInfo("sort-table", sortWeightId, sortTyp, 0, vc, 1);
        } else {
            console.log("分拣/报损称重异常：" + data);
        }
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
        }
    }
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        console.log("wcs_to_wms:" + JSON.stringify(data));
        const boxCode = obj.boxCode;
        if (obj.code == 0) {
        } else {
        }
    }
}

function send(obj, onEvent) {
    if (socket.connected) {
        socket.emit(onEvent, obj);//{msgContent: data}是一个json对象,到了服务端会反序列化
    } else {
        console.log("socketIo未连接");
    }
}

//称重
function checkWeight(data) {
    const list = $('#sort-table').bootstrapTable('getData');

    console.log("称重list：" + JSON.stringify(list));
    $('#check-weight').hide();
    /*let boxWeight = $('#total-weight').val();
    if (!checkPrice(boxWeight)) {
        console.log("价格不符" + boxWeight);
        $('#check-weight').show();
        return;
    }*/

    if (list.length <= 0) {
        //todo 校验箱子有没其他当前要分拣的原料
        //原料箱没有相关产品的原料
        console.log("........");
        $('#check-weight').show();
        return;
    } else {
        console.log("称重list111：" + JSON.stringify(list[0]));
        const tmp = list[0];
        if (!tmp || !tmp.spuName) {
            console.log("111........");
            $('#check-weight').show();
            return;
        }
    }

    // num.toFixed(2)
    let sortWeight = $('#sort-weight').val();

    //获取选中行
    const rows = $('#sort-table').bootstrapTable('getSelections');
    console.log("选中的行2：" + JSON.stringify(rows));
    if (rows.length > 0) {
        //非正整数校验
        if (!checkPrice(sortWeight)) {
            sortWeight = 0;
        }
        console.log("此次分拣重量：" + sortWeight);
        let weight = parseFloat(sortWeight).toFixed(2);
        console.log("weight:" + weight);
        if (!checkPrice(weight)) {
            weight = 0;
        }
        if (weight < 0) {
            //称重
            $('#total-weight').val(sortWeight);
        } else {
            //货箱入库
            $('#total-weight').val(weight);
        }
        const sortingSpu = rows[0];
        //称重重量，小于每份销售重量的一半，则称重提示
        if ((sortWeight - (parseFloat(sortingSpu.weight) / 2).toFixed(2)) < 0) {
            BootstrapDialog.confirm({
                title: '信息提示',
                message: '当前称重重量为：' + sortWeight + 'g，小于分拣重量。是否继续称重？',
                btnCancelLabel: '取消', // <-- Default value is 'Cancel',
                btnOKLabel: '确定', // <-- Default value is 'OK',
                size: BootstrapDialog.SIZE_NORMAL,
                callback: function (resultConfirm) {
                    if (resultConfirm) {
                        checkWeightInfo(sortingSpu, weight, sortWeight);
                    } else {
                        $('#check-weight').show();
                    }
                }
            });
        } else {
            checkWeightInfo(sortingSpu, weight, sortWeight)
        }
    } else {
        $('#check-weight').show();
        BootstrapDialog.alert("请选中需要分拣的原料！");
    }
}

function checkWeightInfo(sortingSpu, weight, sortWeight) {
    if (weight === 0.00 && sortWeight === 0) {
        //报损，提示重量不符，取消提示再称重后
    } else {
        const rows = $('#sort-table').bootstrapTable('getSelections');
        if (rows.length > 0) {
            const row = rows[0];
            const boxCode = $('#ware-box-code').val();
            let sortIds = new Array();
            sortIds.push(row.id);
            const param = {sortIds: sortIds, boxCode: boxCode, packId: row.packId};
            console.log("row===" + JSON.stringify(row));
            param["sortWeight"] = sortWeight;
            param["weight"] = row.weight;
            param["quantity"] = row.quantity;
            param["bigProduct"] = 1;
            param["standard"] = row.standard;

            const inErrInfo = updateSortTaskDetail(param);

            updateSortTable(inErrInfo, row, sortWeight);

        }
    }
    //延时一下，房子做操人员不理解认为没点到
    setTimeout(function () {
        $('#check-weight').show();
    }, 500);
}

//分拣处理
function updateSortTaskDetail(opt) {
    //误差范围内，不更新页面
    let inErr = false;
    const result = {};
    $.ajax({
        type: "POST",
        url: "/wcs/sort/detail/updateSortWeightByIdOfLarge",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            console.log("ppppppppppppp:" + JSON.stringify(data));
            if (data.code == 0) {
                if (data.data && data.data.inError) {
                    console.log("ppppp==========");
                    inErr = data.data.inError;
                    result["inErr"] = inErr;
                }
                result["quantity"] = data.data.quantity;
            } else {
                result["inErr"] = true;
                result["msg"] = data.msg;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
            result["inErr"] = true;
            result["msg"] = "系统异常";
        }
    });
    return result;
}

/**
 * 更新分拣列表，若是分数达成，则删除
 *
 * @param inErrInfo
 * @param row
 */
function updateSortTable(inErrInfo, row, sortWeight) {
    //不在误差范围内，则更新页面
    if (!inErrInfo.inErr) {
        $('#total-weight').val("");
        //更新到右边
        const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
        if (orderRow) {
            console.log(JSON.stringify(orderRow));
            console.log(JSON.stringify(inErrInfo));
            let weight = (orderRow.weight * orderRow.quantity - sortWeight * (orderRow.sortQuantity + inErrInfo.quantity)).toFixed(2);
            const num = orderRow.quantity - (orderRow.sortQuantity + inErrInfo.quantity);
            console.log("剩余称重重量：" + weight + ";num=" + num);
            let sortQuantity = orderRow.sortQuantity;
            if (num > 0) {
                sortQuantity = sortQuantity + 1
            } else {
                sortQuantity = orderRow.quantity;
            }
            //sortWeight是多份的情况下剩余重量为0
            if (weight < 0) {
                weight = 0;
            }

            $('#sort-table').bootstrapTable('updateByUniqueId', {
                id: row.id,
                row: {
                    remainingWeight: parseFloat(weight).toFixed(2),
                    packId: row.packId,
                    sortQuantity: sortQuantity
                }
            });
            console.log("yisys:sortQuantity=" + sortQuantity + ";orderRow.quantity=" + orderRow.quantity);
            if (sortQuantity === orderRow.quantity) {
                $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                const std = $('#sort-table').bootstrapTable('getSelections');
                if (Array.isArray(std) && std.length > 0) {
                    const objBox = std[0];
                    $("#sort-weight").val(objBox.weight);
                    $('#spu-img').attr('src', objBox.imgUrl);
                } else {
                    $("#sort-weight").val("");
                }
            } else {
                $('#sort-table').bootstrapTable('checkBy', {field: 'id', values: [row.id]});
            }
        }

    } else if (inErrInfo.msg) {
        BootstrapDialog.alert(inErrInfo.msg);
    }
}

//根据订单获取的加工任务列表
function initSortTable(opt, list) {
    $('#sort-table').bootstrapTable('destroy');
    $('#sort-table').bootstrapTable({
        url: '/wcs/sort/sortingTask',        // 表格数据来源
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        striped: true,
        uniqueId: 'id',
        singleSelect: true,
        rowStyle: rowStyle,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#form-param").serializeJSON();
            return temp;
        },
        onLoadSuccess: function (data) {
            if (data.code == 0) {
                console.log("6666666666666666" + JSON.stringify(list));
                const sortDetailList = data.data.sortDetailList;
                console.log("777777777777" + JSON.stringify(sortDetailList))
                if (sortDetailList && sortDetailList.length > 0) {
                    //分拣任务列表
                    $("#sort-table").bootstrapTable("load", sortDetailList);

                    const rows = $('#sort-table').bootstrapTable('getData');
                    console.log("第一行：" + JSON.stringify(rows));
                    if (rows.length > 0) {
                        const row = rows[0];
                        //招商演示用，图片以supId.jpg的形式放到/page/img/下
                        console.log("00000000000000:" + JSON.stringify(row))
                        $('#spu-img').attr('src', row.imgUrl);
                        $('#sort-weight').val(row.weight);
                    }
                } else {
                }
            }
        },
        columns: [
            {
                checkbox: true,
                formatter: function (value, row, index) {
                    if (index === 0) {
                        const std = $('#sort-table').bootstrapTable('getSelections');
                        if (Array.isArray(std) && std.length > 0) {
                            return {checked: false};
                        } else {
                            return {checked: true};
                        }
                    }
                }
            }, {
                field: 'spuName',
                align: 'left',
                title: '名称'
            }, {
                field: 'shelfLocation',
                title: '货位'
            }, {
                field: 'quantity',
                title: '数量'
            }, {
                field: 'sortQuantity',
                title: '已分拣数量'
            }, {
                field: 'weight',
                title: '每份重量',
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "background-color": "#007AF5",
                            "font-size": '16px;',
                            "font-weight": "bold",
                            "color": "#FFFFFF"
                        }
                    };
                },
            }, {
                field: "remainingWeight",
                title: "缺少重量",
                cellStyle: function (value, row, index) {
                    return {
                        css: {
                            "background-color": "#F57A00",
                            "font-size": '16px;',
                            "font-weight": "bold",
                            "color": "#FFFFFF"
                        }
                    };
                },
                formatter: function (value, row, index) {
                    if (value) {
                        return value;
                    } else {
                        if (row.weight && row.sortWeight && row.sortWeight > 0) {
                            return (row.weight * row.quantity - row.sortWeight).toFixed(2);
                        }
                    }
                }
            }, {
                field: 'temperatureZoneName',
                title: '所属温区'
            }, {
                field: 'spuId',
                title: '原料',
                visible: false
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                valign: 'middle',
                formatter: actionFormatter,
            }]
    });
}

//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    // result += '<a href="javascript:;" class="btn btn-xs green" onclick="outOfStock(\'' + row.id + '\')" title="缺货"><span class="glyphicon glyphicon-pencil"></span></a>';
    result += '<button type="button" class="btn btn-primary" onclick="outOfStock(\'' + row.id + '\')">缺货</button>';
    return result;
}

//样式
function rowStyle(row, index) {
    if (index === 0) {
        return {
            css: {
                "font-size": '16px;',
                "font-weight": "bold",
                "font-family": 'Microsoft YaHei',
                "background-color": '#CCCC99'
            }
        };
    } else {
        return {css: {"font-size": '16px;', "font-weight": "bold", "font-family": 'Microsoft YaHei'}};
    }
}

//缺货
function outOfStock(sortDetailId) {
    if (!sortDetailId) {
        return;
    }
    const sortDetail = $('#sort-table').bootstrapTable('getRowByUniqueId', sortDetailId);
    if (sortDetail) {
        BootstrapDialog.confirm({
            title: '信息提示',
            message: sortDetail.spuName + '是否确定作缺货处理?',
            btnCancelLabel: '取消', // <-- Default value is 'Cancel',
            btnOKLabel: '确定', // <-- Default value is 'OK',
            size: BootstrapDialog.SIZE_NORMAL,
            callback: function (result) {
                if (result) {
                    sortDetail.status = 4;
                    console.log("sortDetail:" + JSON.stringify(sortDetail));
                    $.ajax({
                        type: "POST",
                        url: "/wcs/sort/detail/updateStatusById",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(sortDetail),
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 0) {
                                $('#sort-table').bootstrapTable('removeByUniqueId', sortDetail.id);
                                const std = $('#sort-table').bootstrapTable('getData');
                                if (Array.isArray(std) && std.length > 0) {
                                    const objBox = std[0];
                                    $("#sort-weight").val(objBox.weight);
                                    $('#spu-img').attr('src', objBox.imgUrl);
                                } else {
                                    $("#sort-weight").val("");
                                }
                            } else {
                                BootstrapDialog.alert(data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            if (XMLHttpRequest.responseJSON) {
                                if (XMLHttpRequest.responseJSON.msg) {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                                } else {
                                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                                }
                            }
                        }
                    });
                }
            }
        });
    }
}

function sortSpuTable(data, boxWeight, spuWeightMap, checked) {
    $('#sort-table').bootstrapTable('destroy');
    $('#sort-table').bootstrapTable({
        data: data,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        singleSelect: true,
        onCheck: function (row, $element) {
            console.log("选中的行3：" + JSON.stringify(row));
            //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
            const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
            if (orderRow) {
                $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                insertRow(orderRow, 'sort-table', true);
            }
        },
        rowStyle: rowStyle,
        columns: [
            {
                checkbox: true,
                formatter: function (value, row, index) {
                    if (index == 0) {
                        if (!checked) {
                            //初始化，未选中行时处理，只取货箱内相同品类的总重量
                            boxWeight = spuWeightMap.get(row.spuId);
                        }
                        if (!checkPrice(boxWeight)) {
                            return;
                        }
                        //缺少重量，则下个箱子，称重的是缺少重量的部分，不缺少，则称的是每份重量
                        boxWeight = parseFloat(boxWeight).toFixed(2);
                        console.log("boxWeight:" + boxWeight + ";rowweight:" + row.weight)
                        if (boxWeight >= row.weight) {
                            $('#sort-weight').val(row.weight);
                        } else {
                            $('#sort-weight').val(boxWeight);
                        }

                        //当前需分拣物品货箱，选中后，右边分拣任务列表，置入第一行
                        const orderRow = $('#sort-table').bootstrapTable('getRowByUniqueId', row.id);
                        if (orderRow) {
                            $('#sort-table').bootstrapTable('removeByUniqueId', row.id);
                            insertRow(orderRow, 'sort-table', true);
                        }

                        /* if (row.weight && row.sortWeight && row.sortWeight > 0) {
                             const weight = (row.weight * row.quantity - row.sortWeight).toFixed(2);
                             //防止weight为负数
                             if (weight > 0) {
                                 console.log(">>>>>>>>>>>>>>>>1" + weight);
                                 $('#sort-weight').val(weight);
                             } else {
                                 console.log(">>>>>>>>>>>>>>>>2" + row.weight);
                                 $('#sort-weight').val(row.weight);
                             }

                         } else {
                             console.log(">>>>>>>>>>>>>>>>3" + row.weight);
                             $('#sort-weight').val(row.weight);
                         }*/
                        return {checked: true};
                    }
                }
            }, {
                field: 'packId',
                align: 'left',
                title: '包装袋',
                // events: onclickEvent,
                formatter: packsToSelect
            }, {
                field: 'spuName',
                align: 'left',
                title: '名称'
            }, {
                field: 'quantity',
                title: '数量',
                formatter: function (value, row, index) {
                    return value - row.sortQuantity;
                }
            }, {
                field: 'weight',
                title: '每份重量'
            }, {
                field: "remainingWeight",
                title: "缺少重量",
                formatter: function (value, row, index) {
                    if (row.weight && row.sortWeight && row.sortWeight > 0) {
                        if (!checked) {
                            //初始化，未选中行时处理，只取货箱内相同品类的总重量
                            boxWeight = spuWeightMap.get(row.spuId);
                        }
                        let weight = (row.weight * row.quantity - row.sortWeight).toFixed(2);
                        console.log("id:" + row.id + ";weight1:" + weight + "boxWeight:" + boxWeight);
                        weight = (weight - boxWeight).toFixed(2);
                        console.log("weight1:" + weight + "boxWeight:" + boxWeight);
                        //防止weight为负数
                        if (weight > 0) {
                            return (row.weight - boxWeight).toFixed(2);
                        } else {
                            /*console.log("0000" + row.checked);
                            const reWeight = (row.weight * row.quantity - row.sortWeight).toFixed(2);
                            console.log("称重完成或货箱到位的分拣重量：" + reWeight);
                            $('#sort-weight').val(reWeight);*/
                            return 0;
                        }
                    }
                }
            }, {
                field: 'unit',
                title: '单位'
            }, {
                field: 'spuId',
                title: '原料',
                visible: false
            }]
    });
}

//包装袋选中事件
window.onclickEvent = {
    'change .pack-select': function (e, value, row, index) {
        if (!value) {
            value = e.currentTarget.value;
        }
        console.log("选中的包装的值：" + value);
        $('#sort-table').bootstrapTable('updateCell', {
            index: index,
            field: 'packId',
            value: value
        })
    }
}

function demotion() {

    $('#frm-spu-select').html('');
    let html = '';
    html += '<option class="opt-spu-inf"></option>';
    const boxList = $('#box-list-table').bootstrapTable('getData');
    console.log("。。。。。。。。。。。。。。" + JSON.stringify(boxList));
    if (boxList && boxList.length > 0) {
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            if (boxDetail.spuName && boxDetail.id) {
                html += '<option value="' + boxDetail.id + '" class="opt-spu-inf">' + boxDetail.spuName + '</option>';
            }
        }
    }
    $('#frm-spu-select').append(html);
    $('#frm-spu-select').selectpicker('refresh');


    $('#frm-spu-grade-select').html('');
    const opt = {};
    $.ajax({
        type: "POST",
        url: "/wcs/grade/selectList",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    const gradeList = data.data;
                    let spuGradeHtml = '';
                    spuGradeHtml += '<option class="opt-spu-grade-inf"></option>';
                    for (let i = 0; i < gradeList.length; i++) {
                        const spuGrade = gradeList[i];
                        spuGradeHtml += '<option value="' + spuGrade.id + '" class="opt-spu-grade-inf">' + spuGrade.gradeName + '(' + spuGrade.gradeCode + ')' + '</option>';
                    }
                    $('#frm-spu-grade-select').append(spuGradeHtml);
                    $('#frm-spu-grade-select').selectpicker('refresh');
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });

    $('#demotion-standard-select').html('');
    const ops = {};
    $.ajax({
        type: "POST",
        url: "/wcs/grade/standard/selectList",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(ops),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    const standardList = data.data;
                    let standardHtml = '';
                    // standardHtml += '<option class="opt-spu-grade-inf"></option>';
                    for (let i = 0; i < standardList.length; i++) {
                        const standard = standardList[i];
                        standardHtml += '<option value="' + standard.id + '" class="opt-spu-grade-inf" style="height: 30px;padding-top: 5px;">' + standard.standardName + '(' + standard.standardCode + ')' + '</option>';
                    }
                    $('#demotion-standard-select').append(standardHtml);
                    $('#demotion-standard-select').selectpicker('refresh');
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
    $('#frm-demotion-model').modal({
        keyboard: false
    })
}

//商品降级
function demotionClick() {
    $('#demotion-goods-detail-box-code').val($('#ware-box-code').val());
    const info = $("#form-param").serializeJSON();
    const standardList = new Array();
    $("#demotion-standard-select option:selected").each(function () {
        standardList.push($(this).val());
    });
    if (standardList.length <= 0) {
        BootstrapDialog.alert("请选择降级标准项！");
        return;
    }
    info['standardList'] = standardList;
    $.ajax({
        type: "POST",
        url: "/wcs/demotion",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(info),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {

            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

//原料报损
function frmLose() {
    const std = $('#sort-table').bootstrapTable('getData');
    let first = null;
    let checkId = null;
    if (Array.isArray(std) && std.length > 0) {
        const rowsInfo = $('#sort-table').bootstrapTable('getSelections');
        if (rowsInfo.length > 0) {
            first = rowsInfo[0];
        } else {
            first = std[0];
        }
        console.log('bootstrapTable getData 是一个数组（即list）：' + JSON.stringify(first));
    }
    const opt = {boxCode: $('#ware-box-code').val()};
    $('#frm-lose-select').html('');
    let html = '';
    $.ajax({
        type: "POST",
        url: "/wcs/box/detail/selectBoxDetailByBoxCode",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.length > 0) {
                        const boxList = data.data;
                        let selectedInfo = false;
                        for (let i = 0; i < boxList.length; i++) {
                            const boxDetail = boxList[i];
                            if (boxDetail.spuName && boxDetail.id && boxDetail.weight > 0) {
                                if (first != null && first.spuId === boxDetail.spuId && first.skuCode === boxDetail.skuCode && first.specCode === boxDetail.specCode) {
                                    $('#goods-detail-id').val(boxDetail.id);
                                    checkId = boxDetail.id;
                                    html += '<option value="' + boxDetail.id + '" selected class="opt-frm-inf" style="height: 30px;padding-top: 5px;">' + boxDetail.spuName + '(' + boxDetail.skuCode + ')' + '&nbsp;&nbsp;/&nbsp;&nbsp;' + boxDetail.weight + '</option>';
                                }else{
                                    html += '<option value="' + boxDetail.id + '" class="opt-frm-inf" style="height: 30px;padding-top: 5px;">' + boxDetail.spuName + '(' + boxDetail.skuCode + ')' + '&nbsp;&nbsp;/&nbsp;&nbsp;' + boxDetail.weight + '</option>';
                                }

                            }
                        }
                    } else {
                    }
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#check-weight').show();
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });


    $('#frm-lose-select').append(html);

    console.log("checkId:" + checkId);
    if (first != null && checkId != null) {
        $('#frm-lose-select').selectpicker('val', checkId);
    }

    $('#frm-lose-select').selectpicker('refresh');
    $('#frm-lose-model').modal({
        keyboard: false
    })
    clearInterval(sortSetInterval);
    sortWeightId = frmSortWeightIdInfo;
    sortTyp = 1;
    sortWeightInfo("sort-table", sortWeightId, sortTyp, 0, null, 1);
}

//原料报损：取消/报损->false/true
function frmLoseClick(cancel) {
    if (cancel) {
        const id = $('#goods-detail-id').val();
        if (!id) {
            BootstrapDialog.alert("请选择报损原料");
            return;
        }
        const frmLoseWeight = $('#frm-lose-weight').val();
        if (!checkPrice(frmLoseWeight)) {
            BootstrapDialog.alert("输入重量格式不符");
            return;
        }
        const orderRow = $('#box-list-table').bootstrapTable('getRowByUniqueId', id);
        console.log("原料：" + JSON.stringify(orderRow));
        if (orderRow) {
            if (frmLoseWeight > orderRow.weight) {
                BootstrapDialog.alert("报损重量大于货箱内原料重量");
                return;
            } else {
                $('#frm-loss-button').attr("disabled", true);
                $('#from-lose-goods-detail-box-code').val($('#ware-box-code').val());
                const opt = $("#form-frm-lose").serializeJSON();
                const std = $('#sort-table').bootstrapTable('getData');
                if (Array.isArray(std)) {
                    opt['sortTaskDetails'] = std;
                    console.log('bootstrapTable getData 是一个数组（即list）');
                }
                opt['clientId'] = $('#client-id').val();
                opt['boxCode'] = $('#ware-box-code').val();
                opt['dataType'] = "SHBS";
                opt['type'] = 0;
                opt['bigProduct'] = 1;
                $.ajax({
                    type: "POST",
                    url: "/wcs/box/detail/updateFrmLoseById",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(opt),
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            $('#frm-lose-model').modal('hide');
                            // const opt = {boxCode: $('#spu-box-code').text()};
                            if (data.data) {
                                const goodsBoxDetail = data.data;
                                console.log("货箱信息更改前：" + JSON.stringify(orderRow));
                                // $('#box-list-table').bootstrapTable('removeByUniqueId', id);
                                orderRow.weight = goodsBoxDetail.weight;
                                /*if (0.00 == orderRow.weight || orderRow.weight == 0) {
                                    $('#sort-weight').val(0);
                                }*/
                                console.log("货箱信息更改后：" + JSON.stringify(orderRow));
                                insertRow(orderRow, 'box-list-table', true);
                            }
                        } else {
                            $('#frm-loss-button').removeAttr("disabled");
                            BootstrapDialog.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (XMLHttpRequest.responseJSON) {
                            if (XMLHttpRequest.responseJSON.msg) {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                            } else {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                            }
                        }
                    }
                });
            }
        } else {
            BootstrapDialog.alert("报损原料信息不存在");
            return;
        }

    } else {
        console.log("2222222222222");
        // $('#frm-lose-model').modal('hide');
        // $('#goods-detail-id').val("");
        // $('#frm-lose-weight').val("");
        // $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);
    }
}

//查询分拣任务
function sortTask(opt, list) {
    let temp = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/sort/sortingTask",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(temp),
        dataType: "json",
        async: false,//后面需校验货箱是否空箱而入库，异步会造成数据不准确
        success: function (data) {
            console.log("6666666" + JSON.stringify(data));
            if (data.code == 0) {
                if (data.data) {
                    if (data.data.sortDetailList.length > 0) {
                    } else {

                    }
                }
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                }
            }
        }
    });
}

function sortChangeShifts() {
    window.location.href = "../../login";
}


